package com.yanftch.hdc_tools.insertcode.storage

import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.Service
import java.io.*


@Service(Service.Level.PROJECT)
object InsertCodeState : PersistentStateComponent<InsertCodeState.State> {

    // 获取服务实例
    class State {
        var name: String = ""
        var value: String = ""
    }

    var stateBean: State = State()

    override fun getState(): State? {
        return stateBean
    }

    override fun loadState(p0: State) {
        this.stateBean = p0
    }

    public fun setName(name: String) {
        this.stateBean.name = name
    }

    public fun getName(): String {
        return this.stateBean.name
    }

    public fun setValue(value: String) {
        this.stateBean.value = value
    }

    public fun getValue(): String {
        return this.stateBean.value
    }

    // 获取存储路径的文件
    /**
     * 获取存储路径的文件
     * 存储在 PersistentStateComponent 的配置路径下
     * file path1: /Users/yangjianfeng/Library/Application Support/IntelliJIdea2018.2/plugins/insert_code_template/config/insert_code_template.json
     * 沙盒环境下的路径是：/Users/yanfeng/Documents/workspace/SyncCode/hdc_tools/build/idea-sandbox/config/insert_code_template.json
     * 正式环境下的路径是：/Users/yanfeng/Library/Application Support/JetBrains/IntelliJIdea2023.3/insert_code_template.json
     *
     * windows: C:\Users\<username>\AppData\Roaming\<JetBrainsProduct>\<version>\config
     *
     */
    private fun getStateFile(): File {
        val file = File(PathManager.getConfigPath(), "insert_code_template.json") // 存储在 PersistentStateComponent 的配置路径下
        return file
    }

    public fun getAbsolutePath(): String {
        val file = File(PathManager.getConfigPath(), "insert_code_template.json") // 存储在 PersistentStateComponent 的配置路径下
        return file.absolutePath
    }

    public fun getPath(): String {
        val file = File(PathManager.getConfigPath(), "insert_code_template.json") // 存储在 PersistentStateComponent 的配置路径下
        return file.path
    }

    // 存储 JSON 文件
    @Throws(IOException::class)
    fun saveJsonToFile(jsonContent: String?) {
        val file: File = getStateFile()
        FileWriter(file).use { writer ->
            writer.write(jsonContent)
        }
    }

    // 读取 JSON 文件
    @Throws(IOException::class)
    fun loadJsonFromFile(): String? {
        val file = getStateFile()
        if (!file.exists()) {
            return null
        }
        BufferedReader(FileReader(file)).use { reader ->
            val content = StringBuilder()
            var line: String?
            while ((reader.readLine().also { line = it }) != null) {
                content.append(line)
            }
            return content.toString()
        }
    }
}
